define(function(require, exports, module) {
  var $ = require("$");
  var dtUtil = require('datatableutil');
  var loader = require("./loader/loader");
  require("bootstrap_commonrequire");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');

  exports.init = function(param) {

    $(document).ready(function() {
      
      loader.loading("数据加载中……");

      // 加载自定义模板-条件区域
      var template = require("./logVoice.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template,
      });
      new Component({
        renderTo : "queryAreaId"
      });

      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "时间"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      
      var myDataStatus = [ {
          "id" : "-1",
          "text" : "待发送"
        }, {
          "id" : "0",
          "text" : "发送成功"
        }, {
          "id" : "1",
          "text" : "发送失败"
        }, {
          "id" : "2",
          "text" : "信控审核中"
        }, {
            "id" : "3",
            "text" : "已取消发送"
          } ];
        $('#status').select2({
          placeholder : "请选择发送状态",
          allowClear : true,
          data : myDataStatus
        });

      function getCondition() {
        //获取查询条件
        var queryStr = "";
        //sessionID
        var session_id = $('#session_id').val();
        if (session_id != '' && session_id != null) {
          queryStr += ("session_id='" + session_id + "';");
        }	
        //主叫
        var batch_number = $('#batch_number').val();
        if (batch_number != '' && batch_number != null) {
          queryStr += ("batch_number like '%" + batch_number + "%';");
        }
        
        var Callee = $('#Callee').val();
        if (Callee != '' && Callee != null) {
          queryStr += ("callee like '%" + Callee + "%';");
        }
        var status = $('#status').val();
        if (status != '' && status != null) {
        	queryStr += ("status='" + status + "';");
        }
        var cust_account = $('#cust_account').val();
        if (cust_account != '' && cust_account != null) {
        	queryStr += ("cust_account='" + cust_account + "';");
        }
        var meet_ims_id = $('#meet_ims_id').val();
        if (meet_ims_id != '' && meet_ims_id != null) {
        	queryStr += ("meet_ims_id='" + meet_ims_id + "';");
        }
        
        // 获取时间查询参数
        var daterange = daterangeCom.getPickerRange();
        if (daterange) {
          var daterange = daterange.split("/");
          var startTime = daterange[0];
          var endTime = daterange[1];
          queryStr += "create_time>='" + startTime + " 00:00:00';create_time<='" + endTime + " 23:59:59'";
        }
        return queryStr;
      }
      
      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "提交时间"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      daterangeCom.setRangeToToday();
      
      //加载表单模板和数据
      var Table = require("table");
      // 查询内容显示
      new Table({
        attrs : {
          id : "datatableid",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.divWrapperId

      });
      //信息显示
      var data_table = $('#datatableid').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "full_numbers", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : param.ajaxUrl,
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.MIN, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }
          // 添加自己的额外参数
          oSettings.jqXHR = $.ajax({
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json) {
              loader.noloading();
              if (json.flag == '000000') {
                dtUtil.successCallback(json, aoData, fnCallback);
              } else {
                oauth2Relogin();
              }
            }
          });

        },
        "aoColumns" : [  
         {
          "sTitle" : "能力类型",
          "bSortable" : false,
          "mData" : "voice_type"
        },{
          "sTitle" : "SessionId",
          "bSortable" : false,
          "mData" : "session_id"
        },{
          "sTitle" : "被叫",
          "bSortable" : false,
          "mData" : "callee",
          "bVisible" : true
        },{
          "sTitle" : "批次号",
          "bSortable" : false,
          "mData" : "batch_number",
          "bVisible" : true
       },{
           "sTitle" : "显号",
           "bSortable" : false,
           "mData" : "displayNumber",
           "bVisible" : true
        },{
	      "sTitle" : "发送状态",
		  "sWidth" : "15%",
	      "bSortable" : false,
	      "mData" : "status",
	      "bVisible" : true,
          "mRender" : function(data, type, full) {
              if (data === "0")
                return "发送成功";
              else if (data === "-1")
                return "待发送";
              else if (data === "3")
            	  return "已取消发送";
              else if (data === "2")
            	  return "信控审核中";
              else if (data === "1")
            	  return "发送失败"; 
              return data;
           }
        }, 
			{
	      "sTitle" : "voiceId",
	      "bSortable" : false,
	      "mData" : "meet_ims_id",
	      "bVisible" : true
	  },{
	      "sTitle" : "计费账户",
	      "bSortable" : false,
	      "mData" : "cust_account",
	      "bVisible" : true
	  },{
	      "sTitle" : "提交时间",
	      "bSortable" : false,
	      "mData" : "create_time",
	      "bVisible" : true
	  },{
	      "sTitle" : "发送时间",
	      "bSortable" : false,
	      "mData" : "schedule_send_time",
	      "bVisible" : true
	  }, {
   	   "sTitle" : '操作',
	   "bSortable" : false, 
		"sWidth" : "9%",
	   "mData" : "id",
	   "mRender" : function(data, status, full){
	      var ret = '';
		   if(full.status == 1 || full.status == 3 ){//发送失败||已取消发送
		   		ret = '<a href="javascript:void(0);" id="'+data+'" class="btn icon-rocket resend" title="重新发送"></a>';
	   	   }else{
	   		    //
	   	   }
		   return ret;
	   }
     }],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
          $('#selectAll').on('change',function(){
        	  var checkValue=arguments[0].srcElement.checked;
        	  $('input[name="voiceid"]').each(function(index,element){
        		  if(element.checked!=checkValue){
          		    element.checked=checkValue;
        		  }      		  
        	  });
          }).css({
        	  'margin':'4px'
          });
        }
      });
      
    
      //查询按钮
      $('#querybtn').click(function() {
          loader.loading("数据加载中……");
          $('#selectAll').attr('checked',false);
    	  data_table.fnFilter("");
    	  return false;
      });

      //重置按钮
      $('#restbtn').click(function() {
          loader.loading("数据加载中……");
          $('#batch_number').val("");
          $('#Caller').val("");
          $("#session_id").val("");
          $("#Callee").val("");
          $("#cust_account").val("");
          $("#meet_ims_id").val("");
          $("#status").select2("val", "");
          $('#selectAll').attr('checked',false);
          daterangeCom.setRangeToToday();
          data_table.fnFilter("");
          return false;
      });
      
      $('#resendbtn').click(function() {
    	  var confirmed = confirm("此操作会按查询条件重新发送，请确认！");
    	  if(confirmed != true){
    		  bootbox.alert("您已取消重发操作");
    		  return false;
    	  }
    	  
          loader.loading("数据加载中……");
          //拼接查询条件
          var queryparam = {};
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q = cond;
          }
          $.ajax({
              url : "/logVoice/resendVoiceByParam.do",
              dataType : "json",
              "data" : queryparam,
              type : "POST",
              success : function(json) {
                  loader.noloading(); 
                  if(json.flag == '000000'){
                	  $("#data_table").dataTable().fnFilter(); 
                	  bootbox.alert("重发成功，共"+json.count+"条，语音通知将会在1分钟后重新发送");
                  } else {
                	  loader.noloading(); 
                	  bootbox.alert("重发操作失败！");                 
                  }
              },
              error : function(s) {
                loader.noloading();
                bootbox.alertTimeout("网络请求失败，请重试！");
              }
            });
    	  
      });
      
      
      //重推按钮
      $("#data_table tbody").on("click", "tr>td>a.icon-rocket", function(e) {
    	  var confirmed = confirm("真的要重新发送吗，请确认！");
    	  if(confirmed != true){
    		  bootbox.alert("您已取消重发操作");
    		  return false;
    	  }
    	  
          loader.loading("数据加载中……");
          var id = this.id;
          $.ajax({
              url : "/logVoice/resendVoiceById.do",
              dataType : "json",
              "data" : {
            	  "id": id
              },
              type : "POST",
              success : function(json) {
                  loader.noloading(); 
                  if(json.flag == '000000'){
                	  $("#data_table").dataTable().fnFilter(); 
                	  bootbox.alert("重发成功,语音通知将会在1分钟后重新发送");
                  } else {
                	  loader.noloading(); 
                	  bootbox.alert("重发操作失败！");                 
                  }
              },
              error : function(s) {
                loader.noloading();
                bootbox.alertTimeout("网络请求失败，请重试！");
              }
            });
      });

      
    });

  };
});
